<template>
  <GroupAllAuditLogs
      v-if="treeStore.treeLinkedTableCategoryId != null"
  ></GroupAllAuditLogs>
  <div class="relative" v-if="treeStore.treeLinkedTableCategoryId == null">
    <div v-if="homeEventTitle == ''">
      <el-tabs
          ref="logTabs"
          v-model="activeName"
          class="demo-tabs"
          :lazy="true"
          @tab-change="auditLogTabsChange"
      >
        <el-tab-pane
            v-for="(tabItem, tabIndex) in tabData()"
            :key="tabIndex"
            :label="tabItem.label"
            :name="tabItem.type"
        >
        </el-tab-pane>
      </el-tabs>
      <!-- <el-row
          class="flex justify-center mb-2.5"
          v-show="converge === 0 && activeName != 3 && activeName != 2"
      >
        <ul class="envet-button">
          <li
              v-for="(item, index) in buttonListData"
              :class="{
              active:
                eventType1 === item.key ||
                (activeName === 1 && eventType > 1 && item.key === ''),
            }"
              :key="index"
              @click="eventTypeFn1(item.key)"
          >
            {{ item.name }}
          </li>
        </ul>
      </el-row> -->
      <el-row
          class="filter-box"
      >
        <!-- <el-button class="mr-2.5" @click="convergeFn">{{ convergeText }}</el-button> -->
        <el-form :model="auditForm" label-width="auto" inline style="max-width: 1200px">
          <el-form-item label="搜索内容:">
            <el-input v-model="auditForm.auditSearch" :style="auditFormLableWidth" placeholder="请输入搜索内容" />
          </el-form-item>
          <el-form-item label="日志类型:">
            <el-select v-model="convergeValue" class="converge-box" :style="auditFormLableWidth">
              <el-option :value="0" label="聚合日志">聚合日志</el-option>
              <el-option :value="1" label="原始日志">原始日志</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="事件类型:" v-if="convergeValue === 0">
            <el-select
                :disabled="convergeValue !== 0 || activeName ===2"
                :style="auditFormLableWidth"
                v-model="auditForm.eventType"
                clearable
                placeholder="请选择"
                style="width: 240px"
                class="ml-2.5"
                @clear="auditForm.eventType = ''"
            >
              <el-option
                  v-for="item in eventTypeOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              >{{ item.label }}
              </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="指纹特征:" v-if="convergeValue === 0">
            <el-input v-model="auditForm.feature" :style="auditFormLableWidth" placeholder="请输入搜索内容" />
          </el-form-item> -->
          <el-form-item label="日期选择:">
            <el-date-picker
              :style="auditFormLableWidth"
              v-model="auditForm.timeString"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              date-format="YYYY-MM-DD"
              time-format="HH:mm:ss"
              @change="timeChange"
          />
          </el-form-item>
          <div class="form-submit">
            <el-button type="primary" @click="convergeFn">搜索</el-button>
          </div>
        </el-form>
      </el-row>
    </div>
    <div class="back" v-else>
      <span @click="$router.push('/home')"
      ><el-icon><ArrowLeft/></el-icon>返回</span
      >
      <h1 class="title">{{ homeEventTitle }}</h1>
    </div>
    <HETTable
        ref="auditLogTable"
        :pageSize="10"
        :tableFields="
        auditForm.converge === 0
          ? treeStore.osType == 'win'
            ? auditLogFields1
            : auditLogFields2
          : treeStore.osType == 'win'
          ? auditLogFields0
          : auditLogFields01
      "
        :tableData="auditLogTableData"
        :enableSearch="false"
        :tableCheckbox="false"
        :total="auditLogTotal"
        @getTableData="getAuditLog"
    >
    </HETTable>
    <el-dialog
        v-if="auditLogDialog"
        v-model="auditLogDialog"
        title="设为可信任策略"
        width="600"
        :center="true"
        :close-on-click-modal="false"
    >
      <el-form class="audit-form">
        <el-form-item label="执行对象"
        ><p class="form-tip">{{ auditLogRowData.operationName }}</p></el-form-item
        >
        <el-form-item label="指纹特征"
        ><p class="form-tip">{{ auditLogRowData.operationFeature }}</p></el-form-item
        >
        <el-form-item label="签名名称"
        ><p class="form-tip">{{ signatureName }}</p></el-form-item
        >
        <el-form-item label="处理方式">
          <el-radio-group v-model="radioValue">
            <el-radio value="0" v-if="activeName != 1">应用程序白名单</el-radio>
            <p class="radio-tip form-tip">
              添加到应用程序白名单中,该规则对所有通用策略生效。
            </p>
            <el-radio value="1" v-if="activeName == 1">USB列表</el-radio>
            <p class="radio-tip form-tip" v-if="activeName == 1">
              添加到应用USB列表,该规则对所有通用策略生效。
            </p>
            <el-radio value="2" :disabled="signatureName == '暂无' || activeName == 1"
            >操作系统白名单
            </el-radio>
            <p class="radio-tip form-tip">
              添加该文件的数字签名到白名单中,带有该数字签名的程序在保护模式下都会放行。
            </p>
            <el-radio value="3" :disabled="activeName == 1">文件指纹特征白名单</el-radio>
            <p class="radio-tip form-tip">
              添加该文件的指纹特征到白名单中,具有该指纹特征的程序在保护模式下都会放行。适用于某些应用软件（如升级频繁的MES系统）可能在运行时会释放临时运行文件并运行（此时文件路径是随机的，采用文件路径做为应用防护匹配策略进行防护时将会被拦截）的特殊场景。
            </p>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="queryAuditLog"> 确定</el-button>
          <el-button @click="auditLogDialog = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, nextTick, toRaw, onMounted, watch, onBeforeUnmount} from "vue";
import {useTreeStore} from "~/utils/pinia/tree.js";
import {ArrowLeft} from "@element-plus/icons-vue";
import {req_getAuditLog} from "~/utils/axios/setting.js";
import HETTable from "~/components/common/HETTable.vue";
import moment from "moment";
import {ElMessage, ElMessageBox} from "element-plus";
import {
  req_getWhitelistFilecert,
  req_setWhitelistFile,
  req_setHard,
  req_getFilecert,
} from "~/utils/axios/programWhitelist.js";
import {useRouter} from "vue-router";
import {req_delUsbList} from "~/utils/axios/index.js";

let $router = useRouter();
const successElMessage = () => {
  ElMessage({
    message: "设置成功",
    type: "success",
  });
};
let treeStore = useTreeStore();
if (JSON.stringify($router.currentRoute.value.query) == "{}") {
  treeStore.openTree();
}
const auditFormLableWidth = 'width:248px'
/**
 *
 * tabs组件
 *
 * ***/
const convergeValue = ref(1)
// 当前选择的tabs页
let activeName = ref(0);
// tabs页ref
const logTabs = ref();
// tabs页的页签
const tabData = () => {
  if (treeStore.osType == "win") {
    return [
      {label: "应用程序", type: 0},
      {label: "外设管理", type: 1},
      {label: "非法外联", type: 2},
      {label: "防火墙", type: 3},
      {label: "全部日志", type: ""},
    ];
  } else {
    return [
      {label: "应用程序", type: 0},
      {label: "USB外设", type: 1},
      {label: "网卡外设", type: 2},
      {label: "非法外联", type: 9},
      {label: "网络防护",type: 8},
      {label: "全部日志", type: ""},
    ];
  }
};


/**
 *
 * table组件
 *
 * ***/
// 搜索表单
const auditForm = reactive({
  converge: 1,
  eventType:'',
  auditSearch: '',
  timeString: ["", ""],
  // feature: '',
  auditForm: 1
})
// eventType
const eventType1 = ref("");
// converge
// const converge = ref(1);
// time
// 表格聚合日志text
// 表格上方中间位置的按钮数据
const eventTypeDefault = [
  {value: "", label: "所有事件"},
  {value: 0, label: "安全事件"},
  {value: 1, label: "威胁事件"},
];
// 事件类型下拉框数据存放
const eventTypeSelect = [
  {value: "", label: "所有事件"},
  {value: 0, label: "安全事件"},
  {value: 1, label: "威胁事件"},
  {value: 10, label: "进程执行"},
  {value: 11, label: "进程拦截"},
  {value: 20, label: "USB接入"},
  {value: 21, label: "USB拦截"},
  {value: 30, label: "网卡发现"},
  {value: 31, label: "网卡拦截"},
  {value: 40, label: "非法外联检测"},
  {value: 41, label: "非法外联拦截"},
  {value: 50, label: "BAT执行"},
  {value: 51, label: "BAT阻止"},
  {value: 60, label: "VBS执行"},
  {value: 61, label: "VBS阻止"},
  {value: 80, label: "文件放行"},
  {value: 81, label: "文件修改"},
  {value: 82, label: "文件删除拦截"},
  {value: 83, label: "文件修改拦截"},
  {value: 90, label: "网络接入"},
  {value: 91, label: "网络拦截"},
  {value: 100, label: "CPL执行"},
  {value: 101, label: "CPL阻止"},
  {value: 110, label: "CMD执行"},
  {value: 111, label: "CMD阻止"},
  {value: 120, label: "MSC执行"},
  {value: 121, label: "MSC阻止"},
  {value: 130, label: "MSI执行"},
  {value: 131, label: "MSI阻止"},
  {value: 140, label: "FON执行"},
  {value: 141, label: "FON阻止"},
  {value: 150, label: "WSF执行"},
  {value: 151, label: "WSF阻止"},
  {value: 160, label: "WSH执行"},
  {value: 161, label: "WSH阻止"},
  {value: 170, label: "REG执行"},
  {value: 171, label: "REG阻止"},
  {value: 180, label: "PS1执行"},
  {value: 181, label: "PS1阻止"},
  {value: 200, label: "控件注册"},
  {value: 201, label: "控件阻止"},
  {value: 202, label: "服务注册"},
  {value: 203, label: "服务阻止"},
  {value: 1110, label: "安全基线检测"},
  {value: 1111, label: "安全基线拦截"},
];

const eventTypeSelectProgram = [
  {value: "", label: "所有事件"},
  {value: 0, label: "安全事件"},
  {value: 1, label: "威胁事件"},
  {value: 10, label: "进程执行"},
  {value: 11, label: "进程拦截"},
  {value: 50, label: "BAT执行"},
  {value: 51, label: "BAT阻止"},
  {value: 60, label: "VBS执行"},
  {value: 61, label: "VBS阻止"},
  {value: 100, label: "CPL执行"},
  {value: 101, label: "CPL阻止"},
  {value: 110, label: "CMD执行"},
  {value: 111, label: "CMD阻止"},
  {value: 120, label: "MSC执行"},
  {value: 121, label: "MSC阻止"},
  {value: 130, label: "MSI执行"},
  {value: 131, label: "MSI阻止"},
  {value: 140, label: "FON执行"},
  {value: 141, label: "FON阻止"},
  {value: 150, label: "WSF执行"},
  {value: 151, label: "WSF阻止"},
  {value: 160, label: "WSH执行"},
  {value: 161, label: "WSH阻止"},
  {value: 170, label: "REG执行"},
  {value: 171, label: "REG阻止"},
  {value: 180, label: "PS1执行"},
  {value: 181, label: "PS1阻止"},
  {value: 200, label: "控件注册"},
  {value: 201, label: "控件阻止"},
  {value: 202, label: "服务注册"},
  {value: 203, label: "服务阻止"},
];
// 如果是防火墙，select只展示两个
const eventTypeSelectIFW = [
  {value: 90, label: "网络接入"},
  {value: 91, label: "网络拦截"},
];

const eventTypeOption = ref(eventTypeSelectProgram)
// tabs点击事件
const auditLogTabsChange = (name) => {
  switch (name) {
    case 0:
      eventTypeOption.value = eventTypeSelectProgram;
      break;
    case 1:
      eventTypeOption.value = eventTypeDefault;
      break;
    case 3:
      eventTypeOption.value = eventTypeSelectIFW;
      break;
    case 9:
      eventTypeOption.value = eventTypeDefault;
      break;
    case 8:
      eventTypeOption.value = eventTypeDefault;
      break;
    default:
      eventTypeOption.value = eventTypeSelect;
      break;
  }
  auditForm.eventType = "";
  eventType1.value = "";
  auditForm.timeString = ["", ""];
  auditForm.auditSearch = '';
  // auditForm.feature = '';
  auditLogTable.value.clearSearch();
  auditLogTable.value.getTableData();
};
// 表格 ref
const auditLogTable = ref();
// 表格数据存放
const auditLogTableData = ref();
// 表格数据数量存放
const auditLogTotal = ref(0);
// 点击操作列时存放行数据的变量
const auditLogRowData = ref();
// 操作列信任函数
const trustFn = (row) => {
  if(row.linuxCreditPolicy){
    return
  }
  if (treeStore.osType == "win") {
    auditLogRowData.value = row;
    auditLogDialog.value = true;
    if (activeName.value != 1) {
      radioValue.value = "0";
    }
    let signatureParams = {
      deviceId: treeStore.treeDeviceId,
      file: row.operationName,
    };
    req_getFilecert(signatureParams).then((res) => {
      signatureName.value = res.data.cert ? res.data.cert : "暂无";
    });
  } else {
    ElMessageBox.confirm("确定要把当前文件添加授信吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      center: true,
      closeOnClickModal: false,
    }).then(() => {
      let setFileParams = {
        deviceId: treeStore.treeDeviceId,
        policyId: 0,
        json: [
          {
            filename: row.operationName,
            filemd5: row.operationFeature,
            termSpec: "",
          },
        ],
      };

      req_setWhitelistFile(setFileParams).then((res) => {
        res.data.succeed ? ElMessage.success("添加成功") : ElMessage.error("添加失败");
        auditLogTable.value.getTableData();
      });
    });
  }
};
// 表格列数据设置
const auditLogFields1 = reactive([
  {name: "operationName", label: "执行对象", width: "300px"},
  {name: "user", label: "用户名称"},
  {name: "eventType", label: "事件类型"},
  {name: "startTime", label: "发生时间", width: "200px"},
  {name: "repeat", label: "重复次数"},
  {name: "operationFeature", label: "指纹特征"},
  {name: "disabled", label: "操作", type: "text", text: "设为可信", ev: trustFn},
]);

const auditLogFields2 = reactive([
  {name: "operationName", label: "执行对象", width: "300px"},
  {name: "user", label: "用户名称"},
  {name: "eventType", label: "事件类型"},
  {name: "startTime", label: "发生时间", width: "200px"},
  {name: "operationFeature", label: "指纹特征"},
  {name: "disabled", label: "操作", type: "text", text: "设为可信", ev: trustFn},
]);

const auditLogFields0 = reactive([
  {name: "operationName", label: "执行对象", width: "300px"},
  {name: "user", label: "用户名称"},
  {name: "eventType", label: "事件类型"},
  {name: "startTime", label: "发生时间", width: "200px"},
  {name: "exesum", label: "执行次数"},
  {name: "stopsum", label: "拦截次数"},
  {name: "operationFeature", label: "指纹特征"},
  {name: "disabled", label: "操作", type: "text", text: "设为可信", ev: trustFn},
]);

const auditLogFields01 = reactive([
  {name: "operationName", label: "执行对象", width: "300px"},
  {name: "user", label: "用户名称"},
  {name: "eventType", label: "事件类型"},
  {name: "startTime", label: "发生时间", width: "200px"},
  {name: "repeat", label: "重复次数"},
  {name: "operationFeature", label: "指纹特征"},
  {name: "disabled", label: "操作", type: "text", text: "设为可信", ev: trustFn},
]);
const homeEventTitle = ref("");
onMounted(() => {
  let routeQuery = $router.currentRoute.value.query;
  console.log(routeQuery);
  if (JSON.stringify(routeQuery) != "{}") {
    homeEventTitle.value = routeQuery.homeEventTitle;
    treeStore.treeDeviceId = routeQuery.deviceId;
    auditForm.converge = parseInt(routeQuery.converge);
    auditForm.eventType = parseInt(routeQuery.eventType);
    auditForm.timeString[0] = routeQuery.startTime;
    auditForm.timeString[1] = routeQuery.endTime;
    auditLogTable.value.getTableData();
  }
});
// 表格数据请求
const getAuditLog = async (countParams, searchParams, search, isSearch) => {
  if (!treeStore.treeDeviceId) {
    treeStore.treeLinkedTableCategoryId = 1;
    auditLogTable.value.finish();
    return;
  }
  let auditLogParams = isSearch ? {
    page: searchParams.$page,
    size: searchParams.$limit,
    type: activeName.value, //日志类型
    converge: auditForm.converge, //日志类型，0-原始日志，1-聚合日志
    startTime: "",
    endTime: "",
  } : {
    page: searchParams.$page,
    size: searchParams.$limit,
    type: activeName.value, //日志类型
    startTime: auditForm.timeString ? (auditForm.timeString[0] ? auditForm.timeString[0] : "") : "",
    endTime: auditForm.timeString ? (auditForm.timeString[1] ? auditForm.timeString[1] : "") : "",
    converge: auditForm.converge, //日志类型，0-原始日志，1-聚合日志
    key: auditForm.auditSearch, //模糊查询
    eventType: auditForm.eventType || eventType1.value, //事件类型
    // operationFeature: auditForm.feature
  };
  if (JSON.stringify($router.currentRoute.value.query) != "{}") {
    delete auditLogParams.key;
    delete auditLogParams.type;
    if (homeEventTitle.value != "今日威胁") {
      delete auditLogParams.eventType;
    }
  }
  if (activeName.value == 2) {
    delete auditLogParams.eventType;
  }
  await req_getAuditLog(treeStore.treeDeviceId, auditLogParams).then((res) => {
    const filterEventType = (type) => {
      let arr = eventTypeSelect.filter((item) => {
        return item.value == type;
      });
      return arr ? arr[0].label : null;
    };
    if (res.data.data) {
      auditLogTableData.value = res.data.data.map((item) => {
        let disabled = false;
        if (res.data.osType == "linux") {
          disabled = item.linuxCreditPolicy;
        } else {
          disabled =
              item.eventType == 10 || item.eventType == 11 || activeName.value == 1 ? 0 : 1;
        }

        return {
          ...item,
          operationFeature: item.operationFeature ? item.operationFeature : "暂无",
          eventType: filterEventType(item.eventType),
          repeat:
            auditForm.converge === 1 && treeStore.osType == "win" ? item.exesum : item.repeat,
          disabled: disabled,
          // item.eventType == 10 || item.eventType == 11 || activeName.value == 1 ? 0 : 1 || item.linuxCreditPolicy,
        };
      });
      auditLogTotal.value = res.data.total;
    }
  }),
      (error) => {
        auditLogTable.value.finish();
        treeStore.treeLinkedTableRef = auditLogTable;
      };
  auditLogTable.value.finish();
  treeStore.treeLinkedTableRef = auditLogTable;
};
// 表格上方中间点击事件
const eventTypeFn = (value) => {
  auditForm.eventType = value;
  eventType1.value = null;
  auditLogTable.value.getTableData();
};

const eventTypeFn1 = (value) => {
  console.log(value);
  eventType1.value = value;
  auditForm.eventType = null;
  auditLogTable.value.getTableData();
};
// 时间组件选择函数
const timeChange = () => {
  auditForm.timeString[0] = moment(auditForm.timeString[0]).format("YYYY-MM-DD HH:mm:ss");
  auditForm.timeString[1] = moment(auditForm.timeString[1]).format("YYYY-MM-DD HH:mm:ss");
};

const dialogSearchCombox = ref(false);

// 聚合日志与原始日志按钮函数
const convergeFn = () => {
  // if (convergeText.value === "聚合日志") {
  //   convergeText.value = "原始日志";
  //   converge.value = 1;
  // } else {
  //   convergeText.value = "聚合日志";
  //   converge.value = 0;
  // }
  auditForm.converge = toRaw(convergeValue.value)
  auditLogTable.value.getTableData();
};
/**
 *
 *  设为可信任模态框
 *
 * ***/
// 模态框ref
const auditLogDialog = ref(false);
// 模态框单选项ref
const radioValue = ref("1");
// 签名名称
const signatureName = ref("暂无");
// 模态框提交函数
const queryAuditLog = async () => {
  let setFileParams = {
    deviceId: treeStore.treeDeviceId,
    policyId: radioValue.value,
    json: [
      {
        filename: auditLogRowData.value.operationName,
        filemd5: auditLogRowData.value.operationFeature,
        termSpec: signatureName.value,
      },
    ],
  };
  let setPeripheralFileParams = {
    deviceId: treeStore.treeDeviceId,
    policyId: 0,
    json: [
      {
        friendlyName: auditLogRowData.value.operationName,
        hardwareID: auditLogRowData.value.operationFeature,
        termSpec: "",
      },
    ],
  };
  if (activeName.value == 1) {
    await req_setHard(setPeripheralFileParams).then(
        (res) => {
          if (res.data.succeed) {
            successElMessage();
          } else {
            ElMessage.error("文件错误");
          }
        },
        (err) => {
          ElMessage.error(err);
        }
    );
  } else {
    await req_setWhitelistFile(setFileParams).then(
        (res) => {
          if (res.data.succeed) {
            successElMessage();
          } else {
            ElMessage.error("文件错误");
          }
        },
        (err) => {
          ElMessage.error(err);
        }
    );
  }

  auditLogDialog.value = false;
  auditLogTable.value.getTableData();
};
onBeforeUnmount(() => {
  treeStore.openTreeFlag = false;
});
</script>

<style lang="scss" scoped>
.back {
  display: flex;
  align-items: center;
  margin-bottom: 15px;

  span {
    display: flex;
    align-items: center;
    cursor: pointer;
  }
}

.envet-button {
  display: flex;
  border-radius: 17px;
  overflow: hidden;
  border: 1px solid $base-color;
  font-size: 14px;
  color: #444;
  cursor: pointer;

  li {
    padding: 5px 18px;
    background-color: #fff;
    border-right: 1px solid $base-color;
  }

  li:last-child {
    border-right: none;
  }
}

li.active {
  background-color: $base-color;
  color: #fff;
}

.filter-box {
  position: relative;
  margin: 0 0 16px 0;
  padding: 24px 24px 8px 24px;
  background-color: #fff;
  border-radius: 6px;
}

.audit-form {
  font-size: 14px;
}

.form-tip {
  display: inline-block;
  width: 100%;
  word-wrap: break-word;
  word-break: break-all;
}

.radio-tip {
  font-size: 12px;
  color: #999;
  margin-left: 22px;
}

.margin-top {
  margin-top: 22px;
}
.converge-box{
  width: 140px;
  margin-right: 10px;
}
:deep(.filter-box .el-form--inline .el-form-item){
  margin-right: 60px;
}
.form-submit{
  position: absolute;
  right: 24px;
  top: 24px;
}
</style>
